package com.example.lleon.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.List;

/**
 * Created by lleon on 2016/12/11.
 */

public class ArticleAdapter extends BaseAdapter {
    // 声明用于装载JSON数据返回值
    private List<ArticleBean> mList;
    // 声明Inflater，用于将Layout转为View
    private LayoutInflater mInflater;
    /*
    *  将JSON返回的数据传递给BaseAdapter
    * */
    public ArticleAdapter(Context context, List<ArticleBean> data) {
        mList = data;
        mInflater = LayoutInflater.from(context);
    }

    /*
    * 返回ListView中Adapter的数据长度
    * */
    @Override
    public int getCount() {
        return mList.size();
    }
    /*
    * 返回当前索引Adapter数据
    * */
    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }
    /*
    * 返回当前Adapter数据的索引
    * */
    @Override
    public long getItemId(int position) {
        return position;
    }
    /*
    * 更改当前ListView
    * */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        /*
        * 为ListView中的数据定义装载的View容器
        * */
        ViewHolder viewHolder = null;
        if(convertView == null) {
            viewHolder = new ViewHolder();
            convertView = mInflater.inflate(R.layout.item_layout, null);

            viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
            viewHolder.tvId = (TextView) convertView.findViewById(R.id.tv_id);

            viewHolder.tvViews = (TextView) convertView.findViewById(R.id.tv_views);
            viewHolder.tvBananas = (TextView) convertView.findViewById(R.id.tv_bananas);
            viewHolder.tvComments = (TextView) convertView.findViewById(R.id.tv_comments);
            viewHolder.tvUrl = (TextView) convertView.findViewById(R.id.tv_url);

            convertView.setTag(viewHolder);
        }else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        /*
        * 将Adapter中的数据添加到View容器中
        * */
        viewHolder.tvTitle.setText(mList.get(position).acTitle);
        viewHolder.tvId.setText(mList.get(position).acId);

        viewHolder.tvViews.setText(mList.get(position).acViews);
        viewHolder.tvBananas.setText(mList.get(position).acBananas);
        viewHolder.tvComments.setText(mList.get(position).acComments);
        viewHolder.tvUrl.setText(mList.get(position).acUrl);

        return convertView;
    }

    /*
    * 定义Adapter数据
    * */
    class ViewHolder {
        public TextView tvTitle, tvId;
        public TextView tvViews, tvBananas, tvComments, tvUrl;
    }
}